import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:sign_tool/sign_apk/sign_apk_bloc.dart';
import 'package:sign_tool/sign_apk/sign_apk_event.dart';
import 'package:sign_tool/sign_apk/sign_apk_view.dart';
import 'package:sign_tool/sign_bloc_observer.dart';
import 'package:sign_tool/upload_apk/upload_apk_cubit.dart';
import 'package:sign_tool/view/sign_form_widget.dart';
// import 'package:window_manager/window_manager.dart';

import 'constants/dimens_constant.dart';
import 'data/apk_info.dart';
import 'data/sign_status.dart';
import 'data/sign_type.dart';
import 'logic/file_manager.dart';
import 'logic/network_request.dart';

Future<void> main() async {
  // WidgetsFlutterBinding.ensureInitialized();
  // // Must add this line.
  // await windowManager.ensureInitialized();
  // await Window.initialize();
  // WindowOptions windowOptions = const WindowOptions(
  //   minimumSize: Size(400, 300),
  //   // maximumSize: Size(400, 300),
  //   //window 限制最小尺寸
  //   size: Size(800, 600),
  //   //
  //   center: true,
  //   backgroundColor: Colors.transparent,
  //   //window 背景颜色，默认设置为透明就好
  //   skipTaskbar: false,
  //   //true 表示在状态栏不显示该应用
  //   alwaysOnTop: false,
  //   //true 表示设置Window一直位于最顶层
  //   titleBarStyle: TitleBarStyle.hidden,
  //   ////hidden 表示隐藏TitleBar（缩放、关闭）
  //   title: "WindowSettingTest",
  //   //设置窗口的标题，
  //   windowButtonVisibility: true, //隐藏
  // );
  // WindowEffect effect = WindowEffect.acrylic;
  // Color color =
  //     Platform.isWindows ? const Color(0x01D86969) : Colors.transparent;
  //
  // windowManager.waitUntilReadyToShow(windowOptions, () async {
  //   await windowManager.show();
  //   await windowManager.focus();
  //   windowManager.setResizable(false); //设置窗口不可缩放
  //   windowManager.setAspectRatio(2); //设置窗口宽高比
  //   windowManager.setHasShadow(true);
  //   windowManager.setBrightness(Brightness.light);
  //
  //   // windowManager.
  //
  //   await Window.setEffect(
  //     effect: WindowEffect.aero,
  //     color: color,
  //   );
  // });
  runApp(const MyApp());
  Get.put<SignStatusManager>(SignStatusManager());
  Bloc.observer = SignBlocObserver();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => SignInfoModel()),
        ChangeNotifierProvider(create: (context) => ApkInfoModel()),
      ],
      child: MultiBlocProvider(
          providers: [
            BlocProvider<SignApkBloc>(
              create: (BuildContext context) => SignApkBloc(),
            ),
            BlocProvider<UploadApkCubit>(
                create: (BuildContext context) => UploadApkCubit())
          ],
          child: const MaterialApp(
            // title: 'Flutter Demo',
            // theme: ThemeData(
            //   colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
            //   useMaterial3: true,
            // ),
            home: MyHomePage(title: '系统应用签名'),
          )),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String filePath = "";
  late NetworkRequestManager manager;
  late FileManager fileManager;
  late SignStatusManager signStatusManager;
  var isShowDialog = false;
  BrnOverlayController? overlayController;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    manager = Get.put<NetworkRequestManager>(NetworkRequestManager());
    fileManager = Get.put<FileManager>(FileManager());
    signStatusManager = Get.find<SignStatusManager>();
  }

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.blueAccent,
          title: Text(widget.title),
        ),
        body: Container(
          padding: const EdgeInsets.all(leftRightPadding),
          child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                const SignFormWidget(),
                Consumer2<ApkInfoModel, SignInfoModel>(
                  builder: (context, apkInfo, signInfo, child) {
                    if (signInfo.isHideDialog) {
                      if (overlayController != null &&
                          overlayController?.isOverlayShowing ==
                              true) {
                        overlayController!.removeOverlay();
                      }
                    }
                    return BrnBottomButtonPanel(
                      enableMainButton: apkInfo.apkPath != null &&
                          signInfo.currentSignInfo != null,
                      mainButtonName: "开始签名",
                      mainButtonOnTap: () async {
                        print("mainButtonOnTap");
                        BrnToast.show("开始签名", context);

                        OverlayEntry overlayEntry =
                        OverlayEntry(builder: (context) {
                          return GestureDetector(
                            onTap: () {
                              print("GestureDetector");
                              // overlayController?.removeOverlay();
                            },
                            child: Container(
                                color: Colors.black.withOpacity(0.4),
                                height: double.infinity,
                                child: Column(
                                  mainAxisAlignment:
                                  MainAxisAlignment.center,
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Container(
                                      alignment: Alignment.center,
                                      height: MediaQuery.of(context)
                                          .size
                                          .height *
                                          0.4,
                                      width: double.infinity,
                                      margin:
                                      const EdgeInsets.symmetric(
                                          vertical: 0,
                                          horizontal: 20),
                                      clipBehavior:
                                      Clip.antiAliasWithSaveLayer,
                                      decoration: const BoxDecoration(
                                          color: Colors.white,
                                          borderRadius:
                                          BorderRadius.all(
                                              Radius.circular(
                                                  20))),
                                      child: SignApkPage(),
                                    )
                                  ],
                                )),
                          );
                        });
                        overlayController = BrnOverlayController._(
                            context, overlayEntry)
                          ..showOverlay();

                        print("isShowDialog:${isShowDialog}");
                        context.read<SignApkBloc>().add(SignEvent(
                            apkInfo.apkPath!,
                            signInfo.currentSignInfo!.typeName));
                      },
                      // secondaryButtonOnTap:() async {
                      //   await Window.setEffect(
                      //     effect: WindowEffect.acrylic,
                      //     color: Color(0xCC222222),
                      //   );
                      // },
                      // secondaryButtonName: "开启毛玻璃效果",
                    );
                  },
                ),
              ]),
        ));



      // WindowBorder(
      //   color: Colors.transparent,
      //   width: 0,
      //   child: Container(
      //       decoration: const BoxDecoration(
      //           borderRadius: BorderRadius.all(Radius.circular(10))),
      //       child: DragToMoveArea(
      //         child: Scaffold(
      //             backgroundColor: Colors.transparent,
      //             appBar: AppBar(
      //               backgroundColor: Colors.blueAccent,
      //               title: Text(widget.title),
      //             ),
      //             body: Container(
      //               padding: const EdgeInsets.all(leftRightPadding),
      //               child: Column(
      //                   crossAxisAlignment: CrossAxisAlignment.center,
      //                   mainAxisAlignment: MainAxisAlignment.start,
      //                   children: [
      //                     const SignFormWidget(),
      //                     Consumer2<ApkInfoModel, SignInfoModel>(
      //                       builder: (context, apkInfo, signInfo, child) {
      //                         if (signInfo.isHideDialog) {
      //                           if (overlayController != null &&
      //                               overlayController?.isOverlayShowing ==
      //                                   true) {
      //                             overlayController!.removeOverlay();
      //                           }
      //                         }
      //                         return BrnBottomButtonPanel(
      //                           enableMainButton: apkInfo.apkPath != null &&
      //                               signInfo.currentSignInfo != null,
      //                           mainButtonName: "开始签名",
      //                           mainButtonOnTap: () async {
      //                             print("mainButtonOnTap");
      //                             BrnToast.show("开始签名", context);
      //
      //                             OverlayEntry overlayEntry =
      //                                 OverlayEntry(builder: (context) {
      //                               return GestureDetector(
      //                                 onTap: () {
      //                                   print("GestureDetector");
      //                                   // overlayController?.removeOverlay();
      //                                 },
      //                                 child: Container(
      //                                     color: Colors.black.withOpacity(0.4),
      //                                     height: double.infinity,
      //                                     child: Column(
      //                                       mainAxisAlignment:
      //                                           MainAxisAlignment.center,
      //                                       mainAxisSize: MainAxisSize.min,
      //                                       children: [
      //                                         Container(
      //                                           alignment: Alignment.center,
      //                                           height: MediaQuery.of(context)
      //                                                   .size
      //                                                   .height *
      //                                               0.4,
      //                                           width: double.infinity,
      //                                           margin:
      //                                               const EdgeInsets.symmetric(
      //                                                   vertical: 0,
      //                                                   horizontal: 20),
      //                                           clipBehavior:
      //                                               Clip.antiAliasWithSaveLayer,
      //                                           decoration: const BoxDecoration(
      //                                               color: Colors.white,
      //                                               borderRadius:
      //                                                   BorderRadius.all(
      //                                                       Radius.circular(
      //                                                           20))),
      //                                           child: SignApkPage(),
      //                                         )
      //                                       ],
      //                                     )),
      //                               );
      //                             });
      //                             overlayController = BrnOverlayController._(
      //                                 context, overlayEntry)
      //                               ..showOverlay();
      //
      //                             print("isShowDialog:${isShowDialog}");
      //                             context.read<SignApkBloc>().add(SignEvent(
      //                                 apkInfo.apkPath!,
      //                                 signInfo.currentSignInfo!.typeName));
      //                           },
      //                           // secondaryButtonOnTap:() async {
      //                           //   await Window.setEffect(
      //                           //     effect: WindowEffect.acrylic,
      //                           //     color: Color(0xCC222222),
      //                           //   );
      //                           // },
      //                           // secondaryButtonName: "开启毛玻璃效果",
      //                         );
      //                       },
      //                     ),
      //                   ]),
      //             )),
      //       )));
  }
}

/// [OverlayWindow] 组件展示隐藏控制器
class BrnOverlayController {
  OverlayEntry? _entry;

  BuildContext context;
  bool _isOverlayShowing = false;

  bool get isOverlayShowing => _isOverlayShowing;

  BrnOverlayController._(this.context, this._entry);

  /// 显示OverlayWindow
  showOverlay() {
    if (_entry != null) {
      Overlay.of(context).insert(_entry!);
      _isOverlayShowing = true;
    }
  }

  /// 移除OverlayWindow
  void removeOverlay() {
    _entry?.remove();
    _entry = null;
    _isOverlayShowing = false;
  }

  bool isShowOverlay() => _isOverlayShowing;
}
